package com.turbo.controller;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;

@RestController
public class PayController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/order")
    public ModelAndView submitOrder() throws UnsupportedEncodingException {

        final MessageProperties properties = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setContentEncoding("utf-8")
                .setHeader("myKey", "myValue")
                .build();


        long orderId = System.currentTimeMillis();
        final Message msg = MessageBuilder.withBody(String.valueOf(orderId).getBytes())
                .andProperties(properties)
                .build();


        amqpTemplate.send("ex.order","key.order",msg);
        System.out.println("订单【"+orderId+"】提交成功，等待支付...");


        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("paying");
        return modelAndView;
    }

    /**
     * 支付，拉取正常队列中的消息，手动确认正常队列中的消息，支付成功
     * 否则消息进入死信队列，支付超时。
     * @return
     */
    @RequestMapping("/pay")
    public ModelAndView payOrder(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("fail");
        rabbitTemplate.execute(new ChannelCallback<String>() {
            @Override
            public String doInRabbit(Channel channel) throws Exception {
                String msg = null;

                final GetResponse getResponse = channel.basicGet("queue.order", false);
                if(null != getResponse){
                    System.out.println("支付成功，订单编号："+new String(getResponse.getBody(),getResponse.getProps().getContentEncoding()));
                    channel.basicAck(getResponse.getEnvelope().getDeliveryTag(),false);
                    modelAndView.setViewName("success");
                    msg =  "订单支付消息，已经确认";
                }
               return msg;
            }
        });
        return modelAndView;
    }
}
